﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model;
using DeHeng_Mes.Model.OrderSingleton;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Model.ViewModel;
using DeHeng_Mes.Utils;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using W03_UI.Model;

namespace DeHeng_Mes.Service
{
    public static class ViewService
    {
        static ViewDao viewDao = new ViewDao();

        static OrderDao orderDao = new OrderDao();

        /// <summary>
        /// 工艺数据推送通用服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="traceId"></param>
        /// <param name="station"></param>
        /// <param name="datas"></param>
        public static void InsertLineMesData<T>(string traceId, string station, List<T> datas) where T : class
        {
            try
            {
                OrderSingletonModel orderSingletonModel = OrderSingleton.GetOrderId(station);

                //获取工序号
                string operationId = MappingTable.GetOperationId(station);

                if (orderSingletonModel == null || datas == null || datas.Count <= 0)
                    return;

                //拿到唯一标识
                string code = Tools.GetHashCodeFromPushMes(orderSingletonModel.OrderId, traceId, orderSingletonModel.OrderCreateTime);

                List<KeyValuePair<string, string>> keyValuePairs = new List<KeyValuePair<string, string>>();

                foreach (var data in datas)
                {
                    //将拉铆工艺数据转成dic
                    List<KeyValuePair<string, string>> list = data.ToPropertyDictionary();

                    keyValuePairs.AddRange(list);
                }

                List<LineMesDataTraceTech> lineMesDataTraceTechs = new List<LineMesDataTraceTech>();

                DateTime now = DateTime.Now;

                foreach (var item in keyValuePairs)
                {
                    if (string.IsNullOrEmpty(item.Value) || item.Key.Equals("Id"))
                        continue;

                    LineMesDataTraceTech lineMesDataTraceTech = new LineMesDataTraceTech()
                    {
                        CreateTime = now,
                        DataFrom = "DEH-W04",
                        DataId = code,
                        DataTraceTechId = Guid.NewGuid().ToString(),
                        Process = operationId,
                        SubEqptId = station,
                        UserId = "",
                        VarName = item.Key,
                        Value = item.Value,
                    };

                    lineMesDataTraceTechs.Add(lineMesDataTraceTech);
                }

                if (lineMesDataTraceTechs.Count > 0)
                {
                    int count = viewDao.PushOperationData(lineMesDataTraceTechs);

                    Tools.ProduceLogText($"[{station}]推送了[{count}]条数据，组装条目[{keyValuePairs.Count}]条数据，追溯码为:[{traceId}]");
                }
            }
            catch (Exception e)
            {
                Tools.ProduceLogTextError($"[{station}]推送数据失败，错误信息：{e.Message}");
            }
        }
        
        /// <summary>
        /// 推送组成关系
        /// </summary>
        public static void InsertDtl(List<string> traceCodes, string station, string operation, string traceCode ,OrderStatus order)
        {
            try
            {

                if (order == null)
                    return;

                string code = Tools.GetHashCodeFromPushMes(order.OrderId, traceCode, order.OrderIssuedTime);

                viewDao.PushBatchData(new LineMesDataDtl()
                {
                    DataDtlId = Guid.NewGuid().ToString(),
                    DataFrom = "DEH-W04",
                    DataId = code,
                    CreateTime = DateTime.Now,
                    TraceId = traceCodes[1],
                    BatchId = "",
                    DeviceId = "",
                    Count = 1,
                    ProcessId = operation
                },station);
            }
            catch (Exception e)
            {
                Tools.ProduceLogTextError($"[{station}]组成关系推送失败，原因是[{e.Message}]");
            }
        }

        /// <summary>
        /// 出站绑定工单
        /// </summary>
        /// <param name="station"></param>
        public static void CodeBandingOrder(string station, string code)
        {
            try
            {
                if (MappingTable.GetStartStation(station))
                {
                    OrderSingletonModel orderSingletonModel = OrderSingleton.GetOrderId(station);

                    if (orderSingletonModel == null) return;

                    string dataId = Tools.GetHashCodeFromPushMes(orderSingletonModel.OrderId, code, orderSingletonModel.OrderCreateTime);

                    DateTime now = DateTime.Now;

                    orderDao.OrderTraceSave(code, orderSingletonModel.OrderId, now);

                    viewDao.PushPartData(new LineMesData()
                    {
                        OrderId = orderSingletonModel.OrderId,
                        TraceId = code,
                        CreateTime = now,
                        DataFrom = "DEH-W04",
                        DataId = dataId,
                    });
                }
            }
            catch (Exception e)
            {
                Tools.ProduceLogTextError($"[{station}]单件绑定推送失败，原因是[{e.Message}]");
            }
        }

        /// <summary>
        /// 出站绑定工单
        /// </summary>
        public static void CodeBandingStationPush(PartProcess partProcess , OrderStatus order)
        {
            try
            {
                if (order == null) return;

                string dataId = Tools.GetHashCodeFromPushMes(order.OrderId, partProcess.TraceId, order.OrderIssuedTime);

                DateTime now = DateTime.Now;

                if (string.IsNullOrEmpty(partProcess.Operation)) return;

                string stationCode = Tools.GetHashCodeFromPushMes(partProcess.TraceId, partProcess.Operation, partProcess.EndTime);

                // 拼接过站数据进行推送
                int stationDataRecord = viewDao.PushStationData(new LineMesDataTrace()
                {
                    DataId = dataId,
                    DataTraceId = stationCode,
                    Station = partProcess.Station,
                    Process = partProcess.Operation,
                    Result = partProcess.Result,
                    CreateTime = now,
                    StartTime = partProcess.StartTime,
                    EndTime = partProcess.EndTime,
                    DataFrom = "DEH-W04",
                    UserId = "",
                },order.OrderId);

                
            }
            catch (Exception e)
            {
                Tools.ProduceLogTextError($"[{partProcess.Station}]推送过站数据失败，原因是{e.Message}");
            }
        }
    }
}
